# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(tidyverse)
library(magrittr)
library(ggrepel)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

configGet <- function(configData, key) {
  configData %>%
    filter(arg == key) %>%
    .$value
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "../pca2D_plot_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))
baseFamily <- fontFamily

parent <- "./"
createWhenNoExist(parent)

pcDataFileName <- paste0(parent, "/PCA_Score.csv")
pcScoreData <- read_csv(pcDataFileName, col_types = cols(X1 = "c")) %>%
  rename(SampleID = X1)

groupFile <- "group.txt"
sampleInfo <- read_tsv(groupFile) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

xPc <- x %>%
  str_c("PC", .)
yPc <- y %>%
  str_c("PC", .)

pc12 <- pcScoreData %>%
  select(c("SampleID", xPc, yPc)) %>%
  set_colnames(c("SampleID", "xPc", "yPc")) %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(sampleInfo$ClassNote)))


print("***")
pcScoreData$SampleID %>%
  discard(function(x) {
    x %in% sampleInfo$SampleID
  })

pdf(str_c(parent, "/PCA_Score_2D.pdf"), width = width, height = height)

sampleColDf <- read_tsv("Class_Color.txt") %>%
  select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
  deframe()

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

impoPc1 <- parameterData[1, xPc]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- parameterData[1, yPc]
impoPc2 <- round(impoPc2 * 100, 2)

p <- ggplot(pc12, mapping = aes(x = xPc, y = yPc, label = SampleID, colour = ClassNote)) +
  xlab(paste(xPc, "(", impoPc1, "%)", sep = "")) +
  ylab(paste(yPc, "(", impoPc2, "%)", sep = "")) +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = xFont, vjust = 0.5),
        axis.text.y = element_text(size = yFont), legend.position = 'right',
        axis.title.y = element_text(size = yTitleFont), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = legendFont), axis.title.x = element_text(size = xTitleFont),
        panel.grid.major = element_blank(), plot.title = element_text(hjust = 0.5, size = mainTitleFont),
        panel.grid.minor = element_blank(), legend.title = element_text(size = legendTitleFont),
  ) +
  geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_point(aes(colour = factor(ClassNote)), size = 4, stroke = 0)

if (nrow(sampleColDf) == 1) {
  p <- p +
    theme(legend.position = 'none')
}

if (!is.na(legendTitle)) {
  p <- p +
    scale_colour_manual(legendTitle, values = sampleCols)
}else {
  p <- p +
    scale_colour_manual("", values = sampleCols)
}

if (!is.na(mainTitle)) {
  p <- p + ggtitle(mainTitle)
}

if (showSample) {
  p <- p +
    geom_text_repel(segment.size = 0.2, size = 2, family = baseFamily)
}

if (showEllipse) {
  p <- p +
    stat_ellipse(aes(fill = factor(ClassNote)), colour = NA, size = 0.3, level = 0.95, type = "norm",
                 geom = "polygon", alpha = 0.1, show.legend = F) +
    scale_fill_manual("", values = sampleCols)
}

p
dev.off()
